package com.zj.juc.study.completion;

import java.util.concurrent.*;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName CompletableFutureUseDemo
 * @Description CompletableFuture使用示例
 * @createTime 2024年12月21日 15:22
 */
public class CompletableFutureUseDemo {

    public static void main(String[] args) throws Exception {


    }

    /**
     * Future能做的CompletableFuture也能做
     */
    public static void futureTaskCanDo(){
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1秒后出结果"+result);
            return result;
        });
        System.out.println(Thread.currentThread().getName()+"去执行其他任务");
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static void futureCanNotDo() throws Exception{
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("1秒后出结果"+result);
            return result;
        }).whenComplete((result,ex)->{
            //执行结束
            //result:上一步的结果
            //ex:上一步的异常
            if (ex == null){
                System.out.println("no error,result is: "+result);
            }
        }).exceptionally(ex->{
            //异常了
            ex.printStackTrace();
            System.out.println("异常了");
            return  null;
        });
        System.out.println(Thread.currentThread().getName()+"去执行其他任务");
        //守护线程的概念，main线程关闭导致CompletableFuture默认线程池关闭
        //解决方案:主线程延时三秒
        TimeUnit.SECONDS.sleep(3);
    }


    /**
     * 使用自定义线程池避免主线程阻塞的解决方案
     */
    private static void useExecutorAvoidMainThreadSleep(){
        //使用自定义线程池避免main主线程需要阻塞
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName());
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("1秒后出结果"+result);
                return result;
            },executorService).whenComplete((result,ex)->{
                //执行结束
                //result:上一步的结果
                //ex:上一步的异常
                if (ex == null){
                    System.out.println("no error,result is: "+result);
                }
            }).exceptionally(ex->{
                //异常了
                ex.printStackTrace();
                System.out.println("异常了");
                return  null;
            });
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }


}
